using System;
using System.Collections.Generic;
using System.Windows.Forms;
using WegasManagementSystem.BLL;
using WegasManagementSystem.Models;

namespace WegasManagementSystem.Forms
{
    public partial class DepartmentForm : Form
    {
        private DepartmentBLL departmentBLL;
        private EmployeeBLL employeeBLL;
        private int? editingDeptId = null;

        public DepartmentForm()
        {
            InitializeComponent();
            departmentBLL = new DepartmentBLL();
            employeeBLL = new EmployeeBLL();
        }

        private void DepartmentForm_Load(object sender, EventArgs e)
        {
            // 加载部门列表
            LoadDepartments();

            // 加载员工列表（用于选择部门负责人）
            LoadEmployees();
        }

        private void LoadDepartments()
        {
            try
            {
                List<Department> departments = departmentBLL.GetAllDepartments();
                dgvDepartments.DataSource = departments;
                
                // 可能的显示调整
                dgvDepartments.Columns["DeptId"].HeaderText = "部门ID";
                dgvDepartments.Columns["DeptName"].HeaderText = "部门名称";
                dgvDepartments.Columns["DeptCode"].HeaderText = "部门代码";
                dgvDepartments.Columns["ParentId"].HeaderText = "上级部门ID";
                dgvDepartments.Columns["ManagerId"].HeaderText = "部门负责人ID";
                dgvDepartments.Columns["CreatedTime"].HeaderText = "创建时间";
                dgvDepartments.Columns["UpdatedTime"].HeaderText = "更新时间";
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载部门列表失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadEmployees()
        {
            try
            {
                List<Employee> employees = employeeBLL.GetAllEmployees();
                
                // 添加一个空选项
                Employee emptyEmployee = new Employee { EmpId = 0, Name = "-- 无 --" };
                employees.Insert(0, emptyEmployee);
                
                // 绑定到下拉框
                cboManager.DataSource = employees;
                cboManager.DisplayMember = "Name";
                cboManager.ValueMember = "EmpId";
                
                // 绑定父部门下拉框
                List<Department> departments = departmentBLL.GetAllDepartments();
                Department emptyDept = new Department { DeptId = 0, DeptName = "-- 无 --" };
                departments.Insert(0, emptyDept);
                
                cboParentDept.DataSource = departments;
                cboParentDept.DisplayMember = "DeptName";
                cboParentDept.ValueMember = "DeptId";
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载员工列表失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            // 清空输入框，准备添加新部门
            ClearInputs();
            editingDeptId = null;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证输入
                if (string.IsNullOrEmpty(txtDeptName.Text))
                {
                    MessageBox.Show("部门名称不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 创建部门对象
                Department department = new Department
                {
                    DeptName = txtDeptName.Text,
                    DeptCode = txtDeptCode.Text,
                    ParentId = (int)cboParentDept.SelectedValue == 0 ? null : (int?)cboParentDept.SelectedValue,
                    ManagerId = (int)cboManager.SelectedValue == 0 ? null : (int?)cboManager.SelectedValue
                };

                bool success;
                
                if (editingDeptId.HasValue)
                {
                    // 更新现有部门
                    department.DeptId = editingDeptId.Value;
                    success = departmentBLL.UpdateDepartment(department);
                    if (success)
                    {
                        MessageBox.Show("部门信息更新成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    // 添加新部门
                    int newId = departmentBLL.AddDepartment(department);
                    success = newId > 0;
                    if (success)
                    {
                        MessageBox.Show("部门添加成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }

                if (success)
                {
                    // 重新加载部门列表
                    LoadDepartments();
                    ClearInputs();
                    editingDeptId = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存部门信息失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dgvDepartments.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择要删除的部门", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            int deptId = (int)dgvDepartments.SelectedRows[0].Cells["DeptId"].Value;
            string deptName = dgvDepartments.SelectedRows[0].Cells["DeptName"].Value.ToString();

            if (MessageBox.Show($"确定要删除部门\"{deptName}\"吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    bool success = departmentBLL.DeleteDepartment(deptId);
                    if (success)
                    {
                        MessageBox.Show("部门删除成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LoadDepartments();
                        ClearInputs();
                        editingDeptId = null;
                    }
                    else
                    {
                        MessageBox.Show("部门删除失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("删除部门失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void dgvDepartments_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvDepartments.SelectedRows.Count > 0)
            {
                // 获取选中的部门ID
                int deptId = (int)dgvDepartments.SelectedRows[0].Cells["DeptId"].Value;
                
                // 获取部门详细信息
                Department department = departmentBLL.GetDepartmentById(deptId);
                
                if (department != null)
                {
                    // 在编辑面板显示部门信息
                    editingDeptId = department.DeptId;
                    txtDeptName.Text = department.DeptName;
                    txtDeptCode.Text = department.DeptCode;
                    
                    // 设置下拉框选中项
                    cboParentDept.SelectedValue = department.ParentId.HasValue ? department.ParentId.Value : 0;
                    cboManager.SelectedValue = department.ManagerId.HasValue ? department.ManagerId.Value : 0;
                }
            }
        }

        private void ClearInputs()
        {
            txtDeptName.Text = string.Empty;
            txtDeptCode.Text = string.Empty;
            cboParentDept.SelectedIndex = 0;
            cboManager.SelectedIndex = 0;
        }
    }
} 